package com.huasoft.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.huasoft.domain.Role;
import com.huasoft.util.JDBConnection;

public class RoleDao {

	public Role getByUserId(Integer id) {
		String sql = "select * from role r where r.id=?";
		Connection con = null;
		PreparedStatement ps = null;
		Role role = null;
		ResultSet rs = null;
		try {
			con = JDBConnection.getConnection();
			ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if (rs == null) {
				return null;
			}
			role = new Role();
			if (rs.next()) {
				role.setId(rs.getInt(1));
				role.setName(rs.getString(2));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				JDBConnection.closeConnection(con, ps, rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return role;
	}

	public List<Role> findAll() {
		String sql = "select * from role";
		Connection con = null;
		Statement st = null;
		List<Role> roles = new ArrayList<Role>();
		ResultSet rs = null;
		try {
			con = JDBConnection.getConnection();
			st = con.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				Role role = new Role();
				role.setId(rs.getInt(1));
				role.setName(rs.getString(2));
				roles.add(role);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				JDBConnection.closeConnection(con, st, rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return roles;

	}

}
